/*
 * @lc app=leetcode.cn id=684 lang=typescript
 *
 * [684] 冗余连接
 */

// @lc code=start
class UnionFind {
  parent: number[];
  size: number[];
  count: number;
  constructor(n: number = 0) {
    this.parent = new Array(n).fill(0).map((_, i) => i);
    this.size = new Array(n).fill(1);
    this.count = n;
  }
  find(x: number): number {
    return this.parent[x] === x ? x : (this.parent[x] = this.find(this.parent[x]));
  }
  union(x: number, y: number): void {
    let rx = this.find(x);
    let ry = this.find(y);
    if (this.size[rx] > this.size[ry]) {
      [rx, ry] = [ry, rx];
    }
    this.size[ry] += this.size[rx];
    this.parent[rx] = ry;
    this.count--;
  }
  isConnected(x: number, y: number): boolean {
    return this.find(x) === this.find(y);
  }
}
function findRedundantConnection(edges: number[][]): number[] {
  const size = edges.length;
  const unionFind = new UnionFind(size + 1);

  for (let edge of edges) {
    let [x, y] = edge;
    // 判断是否有连通性，是的话就是一个冗余链接
    if (unionFind.isConnected(x, y)) {
      return edge;
    }
    unionFind.union(x, y);
  }
}
// @lc code=end
